package com.slockerboss.juegos.bolarebota;

import android.graphics.Canvas;

public class HiloLoopJuego extends Thread {

	// atributos
	VistaJuegoBolaRebota v;
	boolean running = false;
	static final int FRAMESPERSECOND = 10;

	long startTime;
	long sleepTime;

	public HiloLoopJuego(VistaJuegoBolaRebota vista) {
		this.v = vista;
	}

	@Override
	public void run() {
		long ticksPorSegundo = 100 / FRAMESPERSECOND; //le damos 10 milisegundos para q se ejecute cada iterecion del loop
		while (running) {
			Canvas c = null;
			startTime = System.currentTimeMillis();
			try {
				c = v.getHolder().lockCanvas();
				synchronized (v.getHolder()) {
					v.onDraw(c);
				}
			} finally {
				if (c != null) {
					v.getHolder().unlockCanvasAndPost(c);
				}
			}
			sleepTime = ticksPorSegundo
					- (System.currentTimeMillis() - startTime);
			try {
				if (sleepTime > 0)
					sleep(sleepTime);
				else
					sleep(10);
			} catch (Exception e) {
			}
		}
	}

	public void setRunning(boolean run) {
		running = run;
	}
}
